# coding:utf-8
import base64
import datetime
import configparser
import time

from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
import pandas as pd
from flask import Flask, jsonify, \
    request, render_template
from flask_cors import CORS
from flask import session, flash, redirect, url_for
from concurrent.futures import ThreadPoolExecutor, wait
# from flask import send_from_directory
# from flask_sqlalchemy import SQLAlchemy
# from flask.views import MethodView

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
app.config['SECRET_KEY'] = '123456'
# 设置cookie过期时长，秒
app.permanent_session_lifetime = datetime.timedelta(seconds=60*60*3)
# 允许跨域请求
CORS(app, supports_credentials=True)
#
config = configparser.ConfigParser()
config.read('设置.ini')
# 或者使用下面的方法获取整个section的键值对
section = config['mysql']
sql_cfg = dict(section.items())
sql_cfg['port'] = int(sql_cfg['port'])
#
# mysql_url = 'mysql+pymysql://root:123@127.0.0.1:3306/db01'
mysql_url = f'mysql+pymysql://{sql_cfg["user"]}:{sql_cfg["password"]}@{sql_cfg["host"]}:{sql_cfg["port"]}/{sql_cfg["database"]}'
run_port = int(config.get('others', 'runPort'))
engine = create_engine(mysql_url)
username = 'admin'
password = 'admin'
print("sql连接:", mysql_url)
int_fields = ['SrcPort', 'DstPort', 'EvtCount']
# int_fields = ['1']


def model_to_dict(model):
    ret = {col: value for col, value in vars(model).items()}
    return ret


def list_dates(start_date, end_date):
    dates = []
    current_date = start_date
    while current_date <= end_date:
        dates.append(current_date.strftime('%Y-%m-%d'))
        current_date += datetime.timedelta(days=1)
    return dates

def query_data(sql_count, sql_data):
    # 查询数量
    df0 = pd.read_sql(sql=sql_count, con=engine)
    total_a = int(df0.values[0][0])
    # 查询数据
    data_list_a = []
    df = pd.read_sql(sql=sql_data, con=engine)
    df['GenTime'] = df['GenTime'].astype('str')
    for ind in range(df.shape[0]):
        row = df.iloc[ind, :]
        data_list_a.append(row.to_dict())
    return sql_data, total_a, data_list_a


@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        from_data = request.form.to_dict()
        print('from_data', from_data)
        fm_password = from_data['password']
        fm_password = base64.b64decode(fm_password).decode()
        print('fm_password', fm_password)
        if from_data['username'] == username and fm_password == password:
            session['admin_id'] = '1'
            session['name'] = username
            session.permanent = True
            flash('登录成功!')
            # 登录上之后跳转的页面
            print('登录成功')
            return redirect(url_for('index'))
        else:
            print('账号或密码错误')
            flash('账号或密码错误！')
            return redirect(url_for('login'))
    return render_template('login.html')


@app.route('/')
def index():
    user_name = session.get('name')
    print({k: v for k, v in session.items()})
    print('当前用户:', user_name)
    if not user_name:
        flash('当前登录已失效, 请重新登录！')
        return redirect(url_for('login'))
    return render_template('index.html')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=run_port)

